package com.soft.base.log;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.filter.ThresholdFilter;
import ch.qos.logback.core.Context;
import com.alibaba.fastjson.JSON;
import com.soft.base.util.HttpUtil;
import com.soft.base.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
@Slf4j
public class LogUtil {

    private static String app;
    private static String url;

    public static void start(String app, String url) {
        LogUtil.app = app;
        LogUtil.url = url;
        ILoggerFactory lc = (ch.qos.logback.classic.LoggerContext) LoggerFactory.getILoggerFactory();
        ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) lc.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
        LogReportAppender reportAppender = new LogReportAppender();
        reportAppender.setContext((Context) lc);
        reportAppender.setName("reportAppender");
        reportAppender.setApp(app);
        reportAppender.setUrl(url);
        ThresholdFilter filter = new ch.qos.logback.classic.filter.ThresholdFilter();
        filter.setLevel(Level.ERROR.levelStr);
        filter.start();
        reportAppender.addFilter(filter);
        reportAppender.start();
        rootLogger.addAppender(reportAppender);
        log.info("start reportAppender for {} -> {}", app, url);
    }

    public static void report(Map<String, Object> data) {
        if (null == url) {
            return;
        }
        Map<String, Object> param = new HashMap<String, Object>(128);
        param.put("data", JSON.toJSONString(data));
        try {
            HttpUtil.get(url, null, param);
        } catch (Exception e) {
            log.error("LogUtil.error", e);
        }
    }

    public static void report(String... params) {
        if (null == url) {
            return;
        }
        Map<String, Object> map = new HashMap<String, Object>(128);
        int size = 2;
        for (int i = 0; i < params.length; i += size) {
            if (i + 1 < params.length) {
                map.put(params[i], params[i + 1]);
            } else {
                map.put(params[i], "NULL");
            }
        }
        report(map);
    }
}
